package handlers

import (
	"brood-agent2/controller"
	"brood-agent2/utils"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

type NginxInstaller struct {
	PkgUrl         DownloadUrl            `json:"pkg_url"`
	ApplicationDir string                 `json:"application_dir"`
	DependPkg      map[string]DownloadUrl `json:"depend_pkg"`
	ExternalPkg    map[string]DownloadUrl `json:"external_pkg"`
	DependFiles    []DownloadUrl          `json:"depend_files"`
}

type LBNginxInstaller struct {
	NginxConfDir string        `json:"nginx_conf_dir"` // 本次配置需要存放的目录
	DependFiles  []DownloadUrl `json:"depend_files"`
}

func InstallNginxHandler(rw http.ResponseWriter, req *http.Request) {
	res := controller.JsonResponse{
		Code:    0,
		Data:    nil,
		Message: "success",
	}
	body, err := io.ReadAll(req.Body)
	if err != nil {
		controller.RenderJsonResponse(rw, &controller.JsonResponse{controller.CodeError, nil, fmt.Sprint(err)})
		return
	}
	var nginxInstaller NginxInstaller
	err = json.Unmarshal(body, &nginxInstaller)
	if err != nil {
		controller.RenderJsonResponse(rw, &controller.JsonResponse{controller.CodeError, nil, fmt.Sprint(err)})
		return
	}

	utils.Logger.Info(fmt.Sprintf("nginxInstaller: %+v", nginxInstaller))
	err = InstallNginxImpl(nginxInstaller)
	if err != nil {
		res.Code = controller.CodeError
		res.Message = fmt.Sprintf("%s", err)
	}

	controller.RenderJsonResponse(rw, &res)
	return
}

func InstallLBNginxHandler(rw http.ResponseWriter, req *http.Request) {
	res := controller.JsonResponse{
		Code:    0,
		Data:    nil,
		Message: "success",
	}
	body, err := io.ReadAll(req.Body)
	if err != nil {
		controller.RenderJsonResponse(rw, &controller.JsonResponse{controller.CodeError, nil, fmt.Sprint(err)})
		return
	}
	var LBNginxInstaller LBNginxInstaller
	err = json.Unmarshal(body, &LBNginxInstaller)
	if err != nil {
		controller.RenderJsonResponse(rw, &controller.JsonResponse{controller.CodeError, nil, fmt.Sprint(err)})
		return
	}

	utils.Logger.Info(fmt.Sprintf("LBNginxInstaller: %+v", LBNginxInstaller))
	err = InstallLBNginxImpl(LBNginxInstaller)
	if err != nil {
		res.Code = controller.CodeError
		res.Message = fmt.Sprintf("%s", err)
	}

	controller.RenderJsonResponse(rw, &res)
	return
}
